package com.situ.vivamarket.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.situ.vivamarket.dao.AdminDao;
import com.situ.vivamarket.model.Admin;
import com.situ.vivamarket.model.Member;
import com.situ.vivamarket.model.search.AdminSearchBean;
import com.situ.vivamarket.service.AdminService;
import org.jasypt.util.password.PasswordEncryptor;
import org.jasypt.util.password.StrongPasswordEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {
    private AdminDao adminDao;
    PasswordEncryptor pe = new StrongPasswordEncryptor();
    @Autowired
    public void setAdminDao(AdminDao adminDao) {
        this.adminDao = adminDao;
    }

    @Override
    public List<Admin> getAllAdmins(AdminSearchBean asb, Page<?> p) {
        try(Page<?>__= PageHelper.startPage(p.getPageNum(), p.getPageSize())) {
            return adminDao.findAll(asb);
        }
    }

    @Override
    public boolean add(Admin admin) {
        admin.setPassword(pe.encryptPassword(admin.getPassword()));//加密密码
        admin.setCreatedTime(LocalDateTime.now());
        admin.setUpdatedTime(LocalDateTime.now());
        return adminDao.insert(admin)>0;
    }

    @Override
    public int deleteByIds(Integer[] ids) {
        return adminDao.deleteByIds(ids);
    }

    @Override
    public Admin findById(Integer id) {
        return adminDao.findById(id);
    }

    @Override
    public Admin findByName(String name) {
        return adminDao.findByName(name);
    }

    @Override
    public boolean update(Admin admin) {
        if(StringUtils.hasText(admin.getPassword())){
            admin.setPassword(pe.encryptPassword(admin.getPassword()));
        }
        admin.setUpdatedTime(LocalDateTime.now());
        return adminDao.update(admin)>0;
    }

    @Override
    public boolean patch(Admin admin) {
        return adminDao.patch(admin)>0;
    }
}
